package com.spring.Controller;

import com.spring.Controller.Interface.*;
import com.spring.Entity.ContractEntity;
import com.spring.Entity.UserEntity;
import com.spring.Service.Interface.*;
import com.spring.Util.STATUS;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arabira on 2016/8/4.
 */
@Controller
@RequestMapping("/contract")
public class ContractControllerImpl implements ContractController{
    @Autowired
    private ContractService contractService;
    @Autowired
    private UserServie userServie;

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> addContract(ContractEntity contractEntity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String userId = (String) session.getAttribute("SID");
        UserEntity check = new UserEntity();
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        check.setId(userId);
        if (userServie.checkUser(check)) {
            response.put("status", "empty");
            response.put("description", "用户不存在");
            return response;
        }
        if (StringUtils.isBlank(contractEntity.getContractId()) || StringUtils.isBlank(contractEntity.getContractName())) {
            response.put("status", "incomplete");
            response.put("description", "填写的信息不完整");
            return response;
        }
        if(contractEntity.getRemind().toString().equals("2000-01-01")){
            contractEntity.setRemind(null);
        }
        int status = contractService.addContract(contractEntity, userId);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "添加成功");
        }
        else if (status == STATUS.EXISTS) {
            response.put("status", "exists");
            response.put("description", "合同已存在");
        }
        else if (status == STATUS.ID_EMPTY) {
            response.put("status", "error");
            response.put("description", "合同Id为空");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/addByAdmin", method = RequestMethod.POST)
    public Map<String, Object> addContractByAdmin(ContractEntity contractEntity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String userId = (String) session.getAttribute("SID");
        UserEntity check = new UserEntity();
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        check = userServie.findByUserName(contractEntity.getUserId());
//        check.setId(userId);
        if (check==null || userServie.checkUser(check)) {
            response.put("status", "empty");
            response.put("description", "提交人编号不存在");
            return response;
        }
        if (StringUtils.isBlank(contractEntity.getContractId()) || StringUtils.isBlank(contractEntity.getContractName())) {
            response.put("status", "incomplete");
            response.put("description", "填写的信息不完整");
            return response;
        }
        if(contractEntity.getRemind().equals("2001-01-01")){
            contractEntity.setRemind(null);
        }
        int status = contractService.addContract(contractEntity, check.getId());
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "添加成功");
        }
        else if (status == STATUS.EXISTS) {
            response.put("status", "exists");
            response.put("description", "合同已存在");
        }
        else if (status == STATUS.ID_EMPTY) {
            response.put("status", "error");
            response.put("description", "合同Id为空");
        }
        return response;
    }

    //通过excel导入合同，要求excel文件必须为.xls
    @ResponseBody
    @RequestMapping(value = "/excel", method = RequestMethod.POST)
    public Map<String, Object> addContractExcel(MultipartFile file, HttpServletRequest request) throws IOException, BiffException, ParseException {
//        System.out.print("1");
        Map<String, Object> response = new HashMap<>();
        if (file != null) {
            response.put("status","empty");
            response.put("description", "文件为空");
            return response;
        }
        String index = file.getName().substring(file.getName().indexOf("."));
        if (!index.equals(".xls")) {
            response.put("status", "error");
            response.put("description", "非xls文件");
            return response;
        }
        String message = contractService.addByExcel(file);
        if (StringUtils.isBlank(message)) {
            response.put("status", "ok");
            response.put("description", "添加成功");
        }
        else {
            response.put("status", "error");
            response.put("description", message);
        }
        return response;
    }

    //通过excel导入合同，要求excel文件必须为.xls
    @ResponseBody
    @RequestMapping(value = "/byExcel", method = RequestMethod.POST)
    public Map<String, Object> addContractByExcel(MultipartFile file, HttpServletRequest request) throws IOException, BiffException, ParseException {
//        System.out.print("1");
        Map<String, Object> response = new HashMap<>();
        if (file == null) {
            response.put("status","empty");
            response.put("description", "文件为空");
            return response;
        }
//        int i = file.getName().indexOf(".");
//        String index = file.getName().substring(i);
//        if (!index.equals(".xls")) {
//            response.put("status", "error");
//            response.put("description", "非xls文件");
//            return response;
//        }
        String message = contractService.addByExcel(file);
        if (StringUtils.isBlank(message)) {
            response.put("status", "ok");
            response.put("description", "添加成功");
        }
        else {
            response.put("status", "error");
            response.put("description", message);
        }
        return response;
    }
    //TODO：shiro判断角色
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Map<String, Object> updateContract(ContractEntity contractEntity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        if (session.getAttribute("SID").equals("null")) {
            response.put("status", "refuse");
            response.put("decription", "未登录");
            return response;
        }

        if (StringUtils.isBlank(contractEntity.getContractId()) || StringUtils.isBlank(contractEntity.getContractName())) {
            response.put("status", "error");
            response.put("description", "合同号或合同名为空");
            return response;
        }
        if(contractEntity.getRemind().equals("2000-01-01")){
            contractEntity.setRemind(null);
        }
        int status = contractService.updateContract(contractEntity.getId(), contractEntity.getContractName(),
                contractEntity.getStart(), contractEntity.getDeadline(), contractEntity.getRemind(), contractEntity.getTimes(),contractEntity.getWarnOrNor());
        if (status == STATUS.MINUS) {
            response.put("status", "minus");
            response.put("description", "金额不可为负数");
        }
        if (status == STATUS.STARTTIMEERROR) {
            response.put("status", "startTimeError");
            response.put("description", "起始时间非法");
        }
        if (status == STATUS.DEADLINEERROR) {
            response.put("status", "startTimeError");
            response.put("description", "截止时间非法");
        }
        if (status == STATUS.REMINDTIMEERROR) {
            response.put("status", "remindTimeError");
            response.put("description", "提醒时间非法");
        }
        if (status == STATUS.ID_EMPTY) {
            response.put("status", "empty");
            response.put("description", "合同不存在");
        }
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "修改成功");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/upOrDown", method = RequestMethod.POST)
    public Map<String, Object> upOrDown(String contractId, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String userId = (String) session.getAttribute("SID");
        if (StringUtils.isBlank(contractId) || StringUtils.isBlank(userId)) {
            response.put("status", "error");
            response.put("description", "合同号为空或未登录");
            return response;
        }
        response = contractService.onOrOff(contractId);
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/byUserName", method = RequestMethod.POST)
    public Map<String, Object> findContractByUserName(HttpSession session, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String userId = (String) session.getAttribute("SID");
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        response = contractService.findContractByUserId(userId, pageNum, pageSize);
//        response = contractService.findContractAll();
        return response;
    }

    //通过合同ID查合同信息
    @ResponseBody
    @RequestMapping(value = "/byId", method = RequestMethod.POST)
    public Map<String, Object> findContractById(String contractId, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String userId = (String) session.getAttribute("SID");
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        if (StringUtils.isBlank(contractId)) {
            response.put("status", "error");
            response.put("description", "合同号为空");
            return response;
        }
        ContractEntity contractEntity = contractService.findContractById(contractId);
        if (null == contractEntity) {
            response.put("status", "empty");
            response.put("descrition", "合同不存在");
            return response;
        }
        else {
            response.put("status", "ok");
            response.put("body", contractEntity);
            return response;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/byAdmin", method = RequestMethod.POST)
    public Map<String, Object> findContractAll(HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
//        String userId = (String) session.getAttribute("SID");
//        if (StringUtils.isBlank(userId)) {
//            response.put("status", "refuse");
//            response.put("description", "未登录");
//            return response;
//        }
//        pageNum = 0;pageSize=10;
        response = contractService.findContractAll();
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/searchReqByAdmin", method = RequestMethod.POST)
    public Map<String, Object> searchReqByAdmin(String contractId, String contractName, String userName, String start, String deadline, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String startS="";
        String startE="";
        String deadlineS ="";
        String deadlineE ="";

        if(start!=""){
            startS= start+" 00:00:00";
            startE= start+" 00:00:00";
        }else{
            startS = "2000-01-01 00:00:00";
            startE = "9999-12-31 23:59:59";
        }

        if(deadline!=""){
            deadlineS = deadline+" 00:00:00";
            deadlineE = deadline+" 00:00:00";
        }else{
            deadlineS = "2000-01-01 00:00:00";
            deadlineE = "9999-12-31 23:59:59";
        }

        response = contractService.findReqContractByAdmin(contractId,contractName,userName,startS,startE,deadlineS,deadlineE);

        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteContract", method = RequestMethod.POST)
    public Map<String, Object> deleteContractByAdmin(String contractId, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        if (session.getAttribute("SID").equals("null")) {
            response.put("status", "refuse");
            response.put("decription", "未登录");
            return response;
        }
        if (StringUtils.isBlank(contractId)) {
            response.put("status", "error");
            response.put("description", "合同ID为空");
            return response;
        }
        ContractEntity contractEntity = contractService.findContractById(contractId);
        if (contractEntity == null) {
            response.put("status", "error");
            response.put("description", "合同不存在");
            return response;
        }
        int status = contractService.deleteContract(contractId);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "添加成功");
        }
        return response;
    }
}
